package interceptor;

import model.User;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import constant.Msg;

public class DefaultInterceptor implements Interceptor{

	@Override
	public void intercept(Invocation inv) {
		//解决跨域问题
		inv.getController().getResponse().setHeader("Access-Control-Allow-Origin", "*");
		inv.getController().getResponse().setHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE");
		//设置编码
		inv.getController().getResponse().setContentType("application/json;charset=UTF-8");
		//設置token
		inv.getController().getResponse().setHeader("Access-Control-Allow-Headers", "Content-Type, token");
		
		
		//token认证
		String token = inv.getController().getRequest().getHeader("token");
		if(token==null){
			if("/users/".equals(inv.getViewPath()) && "index".equals(inv.getMethodName()) 
					&& "POST".equals(inv.getController().getRequest().getMethod())){
				inv.invoke();
			}else{
				inv.getController().renderJson(Msg.ERROR_UNLOGIN);
			}
		}else{
			if(!User.userCache.exists(token)){
				if("/users/".equals(inv.getViewPath()) && "index".equals(inv.getMethodName()) 
						&& "POST".equals(inv.getController().getRequest().getMethod())){
					inv.invoke();
				}else{
					inv.getController().renderText(Msg.ERROR_UNLOGIN);
				}
			}else{
				inv.invoke();
			}
		}
	}

}
